package com.guinea.core;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import net.sf.navigator.menu.MenuRepository;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderServlet;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.guinea.core.service.MyMenuService;

public class MyContextLoaderServlet extends ContextLoaderServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected static Logger logger = LoggerFactory.getLogger(MyContextLoaderServlet.class);
	
    public void init() throws ServletException {
        super.init();
        setupContext(getServletContext());
    }
    
    public static void setupContext(ServletContext context) {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);
		SessionFactory sessionFactory = (SessionFactory)ctx.getBean("sessionFactory");
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		MyMenuService myMenuService = (MyMenuService) ctx.getBean("myMenuService");
		MenuRepository repository = myMenuService.getRepository();
		MenuRepository defaultRepository = (MenuRepository) context
				.getAttribute(MenuRepository.MENU_REPOSITORY_KEY);
		repository.setDisplayers(defaultRepository.getDisplayers());
//		MenuRepository.MENU_REPOSITORY_KEY.equals("net.sf.navigator.menu.MENU_REPOSITORY")
//		context.getAttribute("net.sf.navigator.menu.MENU_REPOSITORY")
//		((net.sf.navigator.menu.MenuLoader)ctx.getBean("menuLoader")).
		context.setAttribute("repository", repository);
		
		tx.commit();
		
		logger.debug("<=========== Initialization complete [OK]");

	}
}
